/*
 * Title:        CloudScheduler Toolkit
 * Description:  a Toolkit for Modeling and Simulation of Job Scheduling and Resource Provisioning in Cloud System
 * Licence:      GPL - http://www.gnu.org/copyleft/gpl.html
 * Author:       Fuhui Wu
 *
 * Copyright (c) 2013-2014, The National University of Defense Technology, China
 */

package org.nudt.jCloud.simulation;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import org.nudt.jCloud.infrastructure.Slot;
import org.nudt.jCloud.workload.Job;
import org.nudt.jCloud.workload.Task;

public class Batch {
	private int id;
	private Job job;
	private List<Task> taskList;
	private double scheduleTime;
	private double finishTime;
	private double duration;
	
	public Batch(Job job){
		setJob(job);
		taskList = new ArrayList<Task>();
	}
	
	public boolean preemptSlot(Slot slot) {
		for(Task task : taskList){
			if(task.getSlot() == slot){
				if(getFinishTime()>=CloudSchedSIM.getClock()){
					task.cancelAssignToSlot();
					taskList.remove(task);
					return true;
				}else{
					throw new RuntimeException("Cannot throw an already finished task.");
				}
			}
		}
		return false;
	}
	
	public static class SortBatchByScheduleTime implements Comparator<Batch>{
		public int compare(Batch batch1, Batch batch2){
			if(batch1.getScheduleTime() < batch2.getScheduleTime()){
				return 1;
			}else if(batch1.getScheduleTime() > batch2.getScheduleTime()){
				return -1;
			}else{
				return 0;
			}
		}
	}
			
	public void add(Task task){
		taskList.add(task);
	}
	
	public void remove(Task task){
		taskList.remove(task);
	}
	
	public void finish(){
		job.finishBatch(this);
	}
					
	public int size(){
		return taskList.size();
	}	
	
	public Job getJob() {
		return job;
	}
	public void setJob(Job job) {
		this.job = job;
	}
	public List<Task> getTaskList() {
		return taskList;
	}
	public void setTaskList(List<Task> taskList) {
		this.taskList = taskList;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public double getScheduleTime() {
		return scheduleTime;
	}

	public void setScheduleTime(double scheduleTime) {
		this.scheduleTime = scheduleTime;
	}

	public double getFinishTime() {
		return finishTime;
	}

	public void setFinishTime(double finishTime) {
		this.finishTime = finishTime;
	}

	public double getDuration() {
		return duration;
	}

	public void setDuration(double duration) {
		this.duration = duration;
	}
	
}
